from django.contrib import admin
# Register your models here.
from django import forms
from django.contrib import admin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User

class UserAdminForm(forms.ModelForm):
    """管理后台专用表单（包含密码设置）"""
    new_password = forms.CharField(
        label='设置密码',
        widget=forms.PasswordInput,
        required=False,
        strip=False,
        help_text="留空则保持原密码"
    )
    password_confirm = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput,
        required=False,
        strip=False
    )

    class Meta:
        model = User
        fields = ['username', 'is_admin', 'is_banned']  # 你的实际模型字段

    def clean(self):
        cleaned_data = super().clean()
        new_password = cleaned_data.get("new_password")
        password_confirm = cleaned_data.get("password_confirm")

        if new_password or password_confirm:
            if new_password != password_confirm:
                raise forms.ValidationError("两次输入的密码不一致")
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        if new_password := self.cleaned_data.get("new_password"):
            user.set_password(new_password)  # 调用你的模型哈希方法
        if commit:
            user.save()
        return user

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    add_form = UserAdminForm
    add_form_template = 'admin/auth/user/add_form.html'  # 使用Django默认模板

    # 添加用户时的字段布局
    def get_fieldsets(self, request, obj=None):
        if not obj:  # 添加页面
            return [
                (None, {
                    'fields': ('username', 'new_password', 'password_confirm', 'is_admin', 'is_banned'),
                }),
            ]
        # 编辑页面
        return [
            (None, {'fields': ('username','session_token')}),
            ('权限', {'fields': ('is_admin', 'is_banned')}),
            ('个性化',{'fields':('description','topimage','avatar')})
        ]

    # 添加用户时使用的表单
    def get_form(self, request, obj=None, **kwargs):
        if not obj:  # 添加页面
            kwargs['form'] = self.add_form
        return super().get_form(request, obj, **kwargs)

    # 列表页显示
    list_display = ('username', 'is_admin', 'is_banned')

# 需要单独声明（因为用了装饰器）
# admin.site.register(User, UserAdmin)
from .models import Image

@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
    # 列表页显示字段
    list_display = ('id', 'title', 'uploader', 'date', 'display', 'thumbnail_preview')
    list_editable = ('display',)  # 允许直接在列表页修改显示状态
    list_filter = ('display', 'date')  # 添加筛选器
    search_fields = ('title', 'description')  # 添加搜索框
    actions = ['approve_images']  # 添加批量操作
    
    # 自定义字段显示
    def display_status(self, obj):
        return '已审核' if obj.display else '待审核'
    display_status.short_description = '审核状态'
    
    # 缩略图预览
    def thumbnail_preview(self, obj):
        return obj.image_file and f'<img src="{obj.image_file.url}" style="max-height: 50px;" />'
    thumbnail_preview.short_description = '预览'
    thumbnail_preview.allow_tags = True
    
    # 批量审核操作
    @admin.action(description='通过审核')
    def approve_images(self, request, queryset):
        queryset.update(display=True)
        self.message_user(request, f"已通过 {queryset.count()} 张图片的审核")

    # 审核页字段分组
    fieldsets = (
        (None, {
            'fields': ('title', 'description', 'uploader')
        }),
        ('审核设置', {
            'fields': ('display', 'image_file'),
            'classes': ('collapse',)  # 可折叠
        }),
    )

from .models import Tag, ImageTag

class ImageTagInline(admin.TabularInline):
    model = ImageTag
    extra = 1  # 控制默认显示的空表单数量
    fields = ('tag', 'bool_value', 'int_value', 'str_value', 'float_value', 'date_value')
    
    def get_fields(self, request, obj=None):
        """根据标签类型动态显示字段"""
        if obj and obj.tag:
            # 如果是编辑现有对象
            tag_type = obj.tag.tag_type
            if tag_type == 'BOOL':
                return ('tag', 'bool_value')
            elif tag_type == 'INT':
                return ('tag', 'int_value')
            elif tag_type == 'STR':
                return ('tag', 'str_value')
            elif tag_type == 'FLOAT':
                return ('tag', 'float_value')
            elif tag_type == 'DATE':
                return ('tag', 'date_value')
        # 默认情况下显示所有字段（用于新增）
        return super().get_fields(request, obj)

@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ('name', 'tag_type', 'description')
    list_filter = ('tag_type',)
    search_fields = ('name', 'description')
    ordering = ('name',)

@admin.register(ImageTag)
class ImageTagAdmin(admin.ModelAdmin):
    list_display = ('image', 'tag', 'get_value_display')
    list_filter = ('tag',)
    search_fields = ('image__title', 'tag__name')
    raw_id_fields = ('image',)  # 对于大量图片时更友好
    
    def get_value_display(self, obj):
        return obj.get_value()
    get_value_display.short_description = 'Value'
    
    def get_fields(self, request, obj=None):
        """根据标签类型动态显示字段"""
        if obj and obj.tag:
            tag_type = obj.tag.tag_type
            if tag_type == 'BOOL':
                return ('image', 'tag', 'bool_value')
            elif tag_type == 'INT':
                return ('image', 'tag', 'int_value')
            elif tag_type == 'STR':
                return ('image', 'tag', 'str_value')
            elif tag_type == 'FLOAT':
                return ('image', 'tag', 'float_value')
            elif tag_type == 'DATE':
                return ('image', 'tag', 'date_value')
        return super().get_fields(request, obj)